package com.serviceprovider.business.module.admin.license.services.dao.impl;

//~--- non-JDK imports --------------------------------------------------------

import com.serviceprovider.business.module.admin.license.model.License;
import com.serviceprovider.business.module.admin.license.services.dao.interfaces.ILicenseService;
import com.serviceprovider.business.module.common.Page;
import com.serviceprovider.business.module.common.PaginationHelper;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Service;

//~--- JDK imports ------------------------------------------------------------

import java.sql.ResultSet;
import java.sql.SQLException;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service("licenseService")
public class LicenseServiceImpl extends JdbcDaoSupport implements ILicenseService {

    /** Logger for this class and subclasses */
    protected final Log logger = LogFactory.getLog(getClass());

    @Autowired
    public LicenseServiceImpl(@Qualifier("jdbcTemplate") JdbcTemplate jdbcTemplate) {
        setJdbcTemplate(jdbcTemplate);
    }

    /*
     * SecurityService securityService;
     *
     *
     *
     * public SecurityService getSecurityService() {
     *       return securityService;
     * }
     *
     * public void setSecurityService(SecurityService securityService) {
     *       this.securityService = securityService;
     * }
     */
    @Override
    public void deleteLicensesById(int[] idList) {
        final String sql = "delete from adm_license where id = ?";    // $NON-NLS-1$

        for (int anIdList : idList) {
            getJdbcTemplate().update(sql, new Object[] { anIdList });
        }
    }

    @Override
    public List<License> findAll() {
        String        sql  = "select id,name,text,comments,attachments,filename,active from adm_license";    // $NON-NLS-1$
        List          list = getJdbcTemplate().queryForList(sql);
        List<License> ret  = new ArrayList<License>();
        Map           row;
        License       aux;

        for (Object obj : list) {
            row = (Map) obj;
            aux = new License();
            aux.setId(Integer.parseInt(row.get("id").toString()));    // $NON-NLS-1$
            aux.setName((String) row.get("name"));                    // $NON-NLS-1$
            aux.setText((String) row.get("text"));                    // $NON-NLS-1$
            aux.setComments((String) row.get("comments"));            // $NON-NLS-1$
            aux.setAttachments((byte[]) row.get("attachments"));      // $NON-NLS-1$
            aux.setFilename((String) row.get("filename"));            // $NON-NLS-1$
            aux.setActive(Boolean.valueOf("" + row.get("active")));

//          aux.setDescription((String) row.get("description"));
//          aux.setStatus((String) row.get("status"));
//          aux.setComments((String)row.get("comments"));
            ret.add(aux);
        }

        return ret;
    }

    @Override
    public License getLicenseById(int id) {
        RowMapper mapper = new RowMapper() {
            public License mapRow(ResultSet rs, int rowNum) throws SQLException {
                License role = new License();

                LicenseServiceImpl.mapRow(role, rs);

                return role;
            }
        };
        final String sql = "select id,name,text,comments,attachments,filename,active from adm_license where id = ?";    // $NON-NLS-1$

        try {
            return (License) getJdbcTemplate().queryForObject(sql, new Object[] { id }, mapper);
        } catch (EmptyResultDataAccessException e) {
            return null;
        }
    }

    private static void mapRow(License role, ResultSet rs) throws SQLException {
        role.setId(rs.getInt("id"));                        // $NON-NLS-1$
        role.setName(rs.getString("name"));                 // $NON-NLS-1$
        role.setText(rs.getString("text"));                 // $NON-NLS-1$
        role.setComments(rs.getString("comments"));         // $NON-NLS-1$
        role.setAttachments(rs.getBytes("attachments"));    // $NON-NLS-1$
        role.setFilename(rs.getString("filename"));
        role.setActive(rs.getBoolean("active"));
    }

    @Override
    public void insertLicense(License license) {
        final String sql =
            "insert into adm_license (name,text,comments,attachments,filename,active) values(?,?,?,?,?,?)";    // $NON-NLS-1$

        getJdbcTemplate().update(sql, new Object[] {
            license.getName(), license.getText(), license.getComments(), license.getAttachments(),
            license.getFilename(), license.isActive()
        });

        // license.setId(new Integer(12));
        // this.securityService.setLicensePermissions(license);
    }

    @Override
    public void updateLicense(License l) {
        final String sql =
            "update adm_license set name = ? , text = ?, comments = ?, attachments = ?,filename = ?,active = ? where id = ?";    // $NON-NLS-1$

        getJdbcTemplate().update(sql, new Object[] {
            l.getName(), l.getText(), l.getComments(), l.getAttachments(), l.getFilename(), l.isActive(), l.getId()
        });
    }

    @Override
    public Page<License> findAll(int pageNo, int recordSize, String sortColumn, String sortOrder) {
        PaginationHelper<License>       pageHelper = new PaginationHelper<License>();
        ParameterizedRowMapper<License> mapper     = new LicenseRowMapper();
        String                          sql        = "select id,name,text,comments,attachments,filename,active from adm_license order by " + sortColumn
                     + " " + sortOrder;    // $NON-NLS-1$
        String countSql = "SELECT COUNT(*) FROM adm_license";

        return pageHelper.fetchPage(getJdbcTemplate(), countSql, sql, new Object[] {}, pageNo, recordSize, sortColumn,
                                    sortOrder, mapper);
    }

    private static class LicenseRowMapper implements ParameterizedRowMapper<License> {
        @Override
        public License mapRow(ResultSet rs, int index) throws SQLException {
            License license = new License();

            license.setId(rs.getInt("id"));                        // $NON-NLS-1$
            license.setName(rs.getString("name"));                 // $NON-NLS-1$
            license.setText(rs.getString("text"));                 // $NON-NLS-1$
            license.setComments(rs.getString("comments"));         // $NON-NLS-1$
            license.setAttachments(rs.getBytes("attachments"));    // $NON-NLS-1$
            license.setFilename(rs.getString("filename"));
            license.setActive(rs.getBoolean("active"));

            return license;
        }
    }
}



